import Utils from '@/utils/index'
import { View, Text, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Dialog, ImageViewer, Tag } from 'antd-mobile'
import { useState, useEffect, useMemo } from 'react'
import { getBrowserController, getNet, getStorage, getWxSDKParams } from '@/pages/components/utils';
import FileItem from '../myComponent/fileItem'
import Header from '../myComponent/header'
import { useDocumentTitle, useGetFileName, useGetImgInRichText, useGetIsMapArray, useGetOutsideUrl, useResetDate, useTitleCut } from '@/utils/myUtils'
import PopoverDownload from '../myComponent/popoverDownload'
import { useSelector, useDispatch } from 'react-redux'
import LgButton from '../components/button'
import { setIdentityCode, setSysInfo, setToken, setType, setUserInfo } from '@/store/slice'
import { Current } from '@tarojs/runtime'
import { HttpDelete, HttpGet, HttpPut, HttpPost } from '@/network/servers'
import { getBaseUrl, requestSystemUrl } from '@/network/baseUrl'
import Loading from '@/myComponent/load'
import LgEmptyContent from '../components/emptyContent'
import LgCell from '@/pages/components/cell'
import LgInput from '@/pages/components/input'
import LgCheckbox from '@/pages/components/checkbox'
// import LancooSelect from '@/pages/components/LgSelectModal'
import LancooSelect from '@/pages/LGcomponents/LgSelectModalEdu'
import LgSwitch from '@/pages/components/switch'

import './index.scss'
const browserController = getBrowserController()
const net = getNet()
const storage = getStorage()
var wx = require('weixin-js-sdk')

const requireContext = require.context("../images/fileIcon", true, /^\.\/.*\.svg$/);
const svgs = requireContext.keys().map(requireContext);
const keys = requireContext.keys()
let fileObj = {}

keys.map((item, index) => {
    let str = item.replace('./', "").replace('.svg', "")
    fileObj[str] = svgs[index]
})

function App() {
    const dispatch = useDispatch()
    const commonData = useSelector((state: any) => state.commonData)

    const [typeList, setTypeList] = useState<any>([])
    const [showType, setShowType] = useState<boolean>(false)
    const [userVisible, setUserVisible] = useState<boolean>(false)
    const [identityVisible, setIdentityVisible] = useState<boolean>(false)
    const [isOpen, setIsOpen] = useState<boolean>(false)
    const [typeItem, setTypeItem] = useState<any>(null)
    const [typeTitle, setTypeTitle] = useState<any>('')
    const [typeDetail, setTypeDetail] = useState<any>('')
    const [canViewList, setCanViewList] = useState<any>([])
    const [selectUserList, setSelectUserList] = useState<any>([])
    const [identityList, setIdentityList] = useState<any>([])
    const [selectIdentityList, setSelectIdentityList] = useState<any>([])
    const [selectIdentityListNew, setSelectIdentityListNew] = useState<any>([])
    const [officePlatform, setOfficePlatform] = useState<any>({})
    const [group, setGroup] = useState([])
    // const group = [
    //     { label: '管理员', value: 6, checked: false },
    //     { label: '领导', value: 8, checked: false },
    // ]

    const {
        userInfo,
        type,
        token
    } = commonData

    useDocumentTitle('类型设置', false)


    const handleRecall = () => {
        HttpPut({
            url: "/api/bulletin/manage/callback",
            data: {
                bulletinId: typeList.bulletinId
            }
        }).then(() => {
            Taro.navigateBack({ delta: 1 })
            setTimeout(() => {
                Taro.showToast({
                    title: '撤回成功'
                })
            }, 500);
        })
    }

    const recall = () => {
        Dialog.show({
            content: <>
                <View className='custom_confirm_box'>
                    <View className='title'>撤回公告</View>
                    <View className='text'>撤回后其他用户将无法查看
                        确定要撤回该公告吗？</View>
                </View>
            </>,
            closeOnAction: true,
            actions: [
                [
                    {
                        key: 'cancel',
                        text: '取消',
                    },
                    {
                        key: 'delete',
                        text: '撤回',
                        danger: true,
                        onClick: () => handleRecall()
                    },
                ],
            ],
        })
    }

    const del = () => {
        Dialog.show({
            content: <>
                <View className='custom_confirm_box'>
                    <View className='title'>删除公告</View>
                    <View className='text'>删除后将无法查看
                        确定要删除该公告吗？</View>
                </View>
            </>,
            closeOnAction: true,
            actions: [
                [
                    {
                        key: 'cancel',
                        text: '取消',
                    },
                    {
                        key: 'delete',
                        text: '删除',
                        danger: true,
                        onClick: () => {
                            HttpDelete({
                                url: '/api/bulletin/manage/del',
                                data: {
                                    bulletinId: typeList?.bulletinId
                                }
                            }).then(() => {
                                Taro.navigateBack({ delta: 1 })
                                setTimeout(() => {
                                    Taro.showToast({
                                        title: '删除成功'
                                    })
                                }, 500);
                            })
                        }
                    },
                ],
            ],
        })
    }

    const getTypeList = (eduId) => {
        let url = '/api/bulletin/all/type', body = { eduId }

        HttpGet({
            url,
            data: body,
            load: true
        }).then((result) => {
            setTypeList(result);
        })
    }

    // 获取类型负责类型列表
    const getOfficePlatform = () => {
        let url = 'api/common/system/server/info',
            body = {
                sysId: '264'
            }
        HttpGet({
            url,
            data: body
        }).then((officePlatform) => {
            setOfficePlatform(officePlatform);
        })
    }

    const getCommonData = async (params) => {
        HttpGet({ //用户信息
            url: params.baseUrl + '/api/common/user',
            data: {
                token: params.lg_tk || token,
            }
        }).then((userInfo) => {
            dispatch(setUserInfo(userInfo))
            HttpGet({ //学校信息
                url: params.baseUrl + '/api/common/system/info',
                data: {
                    eduId: userInfo.eduId,
                    token: params.lg_tk
                }
            }).then((sysInfo) => {
                dispatch(setSysInfo(sysInfo))
                getTypeList(userInfo.eduId);
                getIdentityList(userInfo.eduId);
            })
        })
    }


    const initWxSdk = async () => {
        const params = getWxSDKParams(['previewImage', 'getLocation'])
        wx.config(params);
        wx.ready(function () {
            // config信息验证后会执行 ready 方法，所有接口调用都必须在 config 接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在 ready 函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在 ready 函数中。
            console.log('ready')
        });
        wx.error(function (res) {
            // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
            console.log(res)
        });
    }

    useEffect(() => {
        if (Utils.getSystemInfo() === 'weapp') {
            initWxSdk()
        }

        if (!token) {
            // 直接跳转当前详情页 需要初始化数据获取
            dispatch(setType(Utils.getQueryVariable('type')))
            let params = {
                lg_tk: Utils.getQueryVariable('lg_tk') || storage.get('token'),
                lg_ic: Utils.getQueryVariable('lg_ic') || storage.get('lg_ic'),
                baseUrl: getBaseUrl()
            }

            dispatch(setToken(params.lg_tk))
            dispatch(setIdentityCode(params.lg_ic))

            if (Utils.getSystemInfo() === 'weapp') {
                requestSystemUrl('220').then((baseUrl) => {
                    params = Object.assign({}, params, { baseUrl })
                    window.baseUrl = baseUrl
                    getCommonData(params).then(getOfficePlatform)
                })
            } else {
                getCommonData(params).then(getOfficePlatform)
            }
        } else {
            let params = {
                lg_tk: Utils.getQueryVariable('lg_tk') || storage.get('token'),
                lg_ic: Utils.getQueryVariable('lg_ic') || storage.get('lg_ic'),
                baseUrl: getBaseUrl()
            }
            getCommonData(params).then(getOfficePlatform)
            // getOfficePlatform();
            // getTypeList(userInfo.schoolId);
        }
    }, [])

    const openItem = (obj) => {
        setShowType(true);
        setTypeItem(obj);
        console.log(obj, 'obj');

        let group1: any = group.concat([]);
        if (obj != '') {
            setTypeTitle(obj.typeName);
            setTypeDetail(obj.remark);
            setSelectUserList(obj?.directorList ? obj?.directorList : []);
            console.log(obj.directorIdentityList.filter(item => item.identityCode !== 'IC0001'))
            setSelectIdentityList(obj?.directorIdentityList ? obj.directorIdentityList.filter(item => item.identityCode !== 'IC0001') : []);
            setSelectIdentityListNew(obj?.directorIdentityList ? obj.directorIdentityList.filter(item => item.identityCode !== 'IC0001') : []);
            setIsOpen(obj.state == '1' ? true : false);
            if (obj.scope.length > 0) {
                group.forEach(item => {
                    item.checked = false;
                    obj.scope.forEach(itm => {
                        if (item.value == itm) {
                            item.checked = true;
                            // group1.push(item)
                        }
                    })
                })
            }
            setCanViewList(group1)
        } else {
            setTypeTitle('');
            setTypeDetail('');
            setSelectUserList([]);
            setSelectIdentityList([]);
            setSelectIdentityListNew([]);
            setIsOpen(false);
            group1.forEach(i => {
                i.checked = false
            })
            setCanViewList(group1)
        }
        console.log(group1)
    }

    const openUser = (type) => {
        if (type === 'user') {
            setUserVisible(true);
        } else {

            setIdentityVisible(true);
        }
    }

    // 获取身份列表
    const getIdentityList = (eduId) => {
        let url = 'api/common/user/type',
            data = {
                eduId,
                // userType: '6,8'
            }
        HttpGet({
            url,
            data,
            load: true
        }).then((result) => {
            let data = result;
            // 基于identityCode参数进行去重
            const uniqueData: any = [];
            // const seenCodes = new Set();
            let tempData = []
            data.forEach(i => {
                tempData.push({ label: i.userTypeName, value: i.identityCode, checked: false })
            })
            setGroup(tempData)
            // data.forEach(item => {
            //     if (!seenCodes.has(item.identityCode)) {
            //         seenCodes.add(item.identityCode);
            //         uniqueData.push(item);
            //     }
            // });
            // console.log(uniqueData, 'result');
            setIdentityList(data);
        })
    }

    const goBack = () => {
        if (showType && !userVisible && !identityVisible) {
            setShowType(false);
            setTypeItem(null);
            setCanViewList([]);
            setTypeTitle('');
            setTypeDetail('');
            setSelectUserList([]);
            setIsOpen(false);
        } else if (userVisible) {
            setUserVisible(false);
        } else if (identityVisible) {
            setIdentityVisible(false);
        } else {
            Taro.navigateBack({
                delta: 1
            })
            // Taro.navigateTo({
            //     url: `pages/admin/index`
            // })
        }
    }

    // 勾选可查看对象
    const changeChecked = (index) => {
        let checked = canViewList[index].checked;
        let newData = [...canViewList];
        canViewList[index].checked = !checked;
        setCanViewList(newData);
    }

    const confirm = (data) => {
        if (!useGetIsMapArray(data)) {
            return
        }
        setSelectUserList(data);
        setUserVisible(false);
    }

    const saveIdentityList = () => {
        setSelectIdentityList(selectIdentityListNew);
        setIdentityVisible(false);
    }

    const changeIdentity = (item) => {
        const index = selectIdentityListNew.findIndex(itm => itm.identityCode === item.identityCode);
        if (index !== -1) {
            // 如果存在，从 selectEquipList 中移除该项
            const newList = [...selectIdentityListNew];
            newList.splice(index, 1);
            setSelectIdentityListNew(newList);
        } else {
            // 如果不存在，将该项添加到 selectEquipList 中
            setSelectIdentityListNew((prevList) => [...prevList, item]);
        }
    }

    //检测是否全为空格
    const isStringEmpty = (str) => {
        // 去除 HTML 标签
        var content = str.replace(/<(.*?)>/g, '');

        // 将 &nbsp; 替换为空格
        content = content.replace(/(&nbsp;|\s)+/g, ' ');

        // 去除空白字符
        content = content.trim();

        // 判断字符串是否为空
        return content.length === 0;
    }

    const saveType = () => {
        if (!typeTitle) {
            Taro.showToast({
                title: '请输入类型名称！',
                icon: 'none',
                duration: 2000,
            })
            return;
        }
        if (isStringEmpty(typeTitle)) {
            Taro.showToast({
                title: '类型名称不能全为空格！',
                icon: 'none',
                duration: 2000,
            })
            return;
        }
        if (!typeDetail) {
            Taro.showToast({
                title: '请输入类型描述！',
                icon: 'none',
                duration: 2000,
            })
            return;
        }
        if (isStringEmpty(typeDetail)) {
            Taro.showToast({
                title: '类型描述不能全为空格！',
                icon: 'none',
                duration: 2000,
            })
            return;
        }
        if (selectUserList.length === 0 && selectIdentityList.length === 0) {
            Taro.showToast({
                title: '请选择负责人或负责身份类型',
                icon: 'none',
                duration: 2000,
            })
            return;
        }
        let selectArr = Array.from(new Set(selectUserList));
        let directorIds: any = [], directorIdentity: any = [];
        selectArr.forEach((item: { userId: string } | unknown) => {
            if (typeof item === 'object' && item !== null && 'userId' in item) {
                directorIds.push((item as { userId: string }).userId);
            }
        });
        selectIdentityList.forEach(item => {
            directorIdentity.push(item.identityCode);
        })
        directorIdentity.unshift('IC0001')
        let scopeArr: any = [];
        canViewList.forEach(item => {
            if (item.checked === true) {
                if (item.value === 0) {
                    scopeArr.push(0, 6, 7, 8);
                } else {
                    scopeArr.push(item.value);
                }
            }
        })
        // console.log('scopeArr', scopeArr);
        if (scopeArr.length === 0) {
            Taro.showToast({
                title: '请选择可查看对象！',
                icon: 'none',
                duration: 2000,
            })
            return;
        }
        Taro.showLoading({
            title: '正在保存~'
        })
        // return;
        let data = {
            typeId: typeItem?.typeId ? typeItem.typeId : '',
            innerTypeId: typeItem?.innerTypeId ? typeItem.innerTypeId : '',
            typeName: typeTitle,
            scope: scopeArr,
            remark: typeDetail,
            eduId: userInfo.eduId,
            state: isOpen === true ? '1' : '0',
            directorIds,
            directorIdentity,
            identityCode: userInfo.identityCode,
        }
        // console.log(data, 'data');
        let url = '/api/bulletin/type/save'
        HttpPost({
            url,
            data
        }).then((result) => {
            Taro.hideLoading();
            setShowType(false);
            setTypeItem(null);
            setCanViewList([]);
            setTypeTitle('');
            setTypeDetail('');
            setSelectUserList([]);
            setIsOpen(false);
            getTypeList(userInfo.eduId);
            Taro.showToast({
                title: '保存成功',
                icon: 'success'
            })
        })
    }

    const handleDel = () => {
        Taro.showModal({
            title: '提示',
            content: '确定要删除该公告类型吗？',
            confirmColor: '#0099ff',
            success: function (res) {
                if (res.confirm) {
                    HttpDelete({
                        url: '/api/bulletin/type/del',
                        data: {
                            typeId: typeItem?.typeId ? typeItem.typeId : '',
                        }
                    }).then(() => {
                        Taro.showToast({
                            title: '删除成功'
                        })
                        setTimeout(() => {
                            // getList()
                            setShowType(false);
                            setTypeItem(null);
                            setCanViewList([]);
                            setTypeTitle('');
                            setTypeDetail('');
                            setSelectUserList([]);
                            setIsOpen(false);
                            getTypeList(userInfo.eduId)
                        }, 1000);
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    }

    if (typeList.length === 0) {
        return <Loading />
    }

    return (
        <View className='type_list'>
            <Header
                title={showType ? userVisible ? '负责用户选择' : identityVisible ? '负责身份选择' : typeItem ? '编辑公告类型' : '添加类型' : '类型设置'}
                isLeft={true}
                isBlod={false}
                goback={goBack}
                className='header_top'
            />
            {
                !showType && useGetIsMapArray(typeList) ?
                    typeList.map((item, index) => {
                        return (
                            <View>
                                <LgCell
                                    title={item.typeName}
                                    key={index}
                                    content=''
                                    showIcon={true}
                                    onClick={() => {
                                        openItem(item)
                                        // handlePopLayer('open', 'type');
                                    }}
                                    type='A'
                                ></LgCell>
                                <View className='horizontal_line'></View>
                            </View>
                        )
                    })
                    :
                    userVisible ?
                        <View className={'select_user_modal ' + (Utils.getSystemInfo() === 'weapp' ? 'is_weapp' : '')}>
                            {/* <LancooSelect
                                token={token}
                                officeUrl={officePlatform.webSvrAddr}
                                selectUserList={selectUserList}
                                onConfirm={confirm}
                                groupUserType={['0', '1', '11']}
                            /> */}
                            <LancooSelect
                                token={token}
                                officeUrl={officePlatform.webSvrAddr}
                                selectUserList={selectUserList}
                                // allSelectObj={allSelectObj}
                                onConfirm={confirm} />
                        </View>
                        :
                        identityVisible ?
                            <View className={'select_identity_modal ' + (Utils.getSystemInfo() === 'weapp' ? 'is_weapp' : '')}>
                                <View className='identity_view'>
                                    {
                                        useGetIsMapArray(identityList) ?
                                            identityList.map((item, index) => {
                                                let isObjectInArray = selectIdentityList.some(obj => obj.identityCode === item.identityCode);
                                                if (item.identityCode === 'IC0001') return

                                                return (
                                                    <View className='identity_item'>
                                                        <LgCheckbox className='check_box' type='B' key={isObjectInArray} default={isObjectInArray ? 1 : 0} onClick={() => changeIdentity(item)}  >{item.userTypeName}</LgCheckbox>
                                                    </View>
                                                )
                                            })
                                            : <View className='empty_container'>
                                                <LgEmptyContent type='B' text={'暂无可选身份'} />
                                            </View>
                                    }
                                </View>
                                <View className='save_identity_btn'>
                                    <LgButton width={200} height={88} className="btn" type='B' onClick={() => saveIdentityList()}>确定</LgButton>
                                </View>
                            </View>
                            :
                            <View className='create_type'>
                                <LgInput
                                    value={typeTitle}
                                    maxLength={8}
                                    type="A"
                                    isNeed={false}
                                    inputName={'类型名称'}
                                    placeholder="请输入类型名称..."
                                    onChange={value => setTypeTitle(value)}
                                ></LgInput>
                                <View className='horizontal_line'></View>
                                <View className='viewable_object'>
                                    <View className='check_obj_span'>可查看对象</View>
                                    <View className='check_obj'>
                                        {
                                            canViewList.map((item, index) => {
                                                return (
                                                    <View className='check_box_div'>
                                                        <LgCheckbox className='check_box' type='B' default={item.checked ? 1 : 0} onClick={() => changeChecked(index)} >{item.label}</LgCheckbox>
                                                    </View>
                                                )
                                            })
                                        }
                                    </View>
                                </View>
                                <View className='horizontal_line'></View>

                                <LgInput
                                    value={typeDetail}
                                    maxLength={200}
                                    type="B"
                                    isNeed={false}
                                    inputName={'描述'}
                                    placeholder="请输入类型详细描述..."
                                    onChange={value => setTypeDetail(value)}
                                ></LgInput>

                                <View className='person_in_charge'>
                                    <LgCell
                                        className='select_user'
                                        title="负责人"
                                        content={
                                            selectUserList.length > 0 ?
                                                <View className='select_user_num'>已选<Text className='user_num_text'>{selectUserList.length}</Text>个对象</View>
                                                : '请选择负责人'
                                        }
                                        showIcon={true}
                                        onClick={() => {
                                            openUser('user');
                                        }}
                                        type='A'
                                    ></LgCell>


                                    <View className='horizontal_line'></View>
                                    <LgCell
                                        className='select_user'
                                        title="负责身份类型"
                                        content={
                                            selectIdentityList.length > 0 ?
                                                <View className='select_user_num'>已选<Text className='user_num_text'>{selectIdentityList.length}</Text>个负责身份</View> : '请选择负责身份'
                                        }
                                        showIcon={true}
                                        onClick={() => {
                                            openUser('identity');
                                        }}
                                        type='A'
                                    ></LgCell>

                                    <View className='horizontal_line'></View>
                                    <View className='is_open'>
                                        <Text className='to_open'>是否启用</Text>
                                        <View className='to_open_view'>
                                            <Text className='to_open_detail'>启用后，负责人可以发布该类型公告</Text>
                                            <View className='is_open_switch'><LgSwitch default={isOpen} key={isOpen ? 1 : 0} onClick={() => setIsOpen(!isOpen)} /></View>
                                        </View>
                                    </View>
                                    <View className='horizontal_line'></View>
                                </View>
                                <View className='footer_option'>
                                    {
                                        typeItem ? <LgButton width={280} height={88} className="btn del" onClick={handleDel} type='D' color='close'>删除</LgButton> : ''
                                    }

                                    <LgButton width={280} height={88} className="btn" type='B' onClick={() => saveType()} >保存</LgButton>
                                </View>
                            </View>
            }



            {/* 创建+ */}
            {
                showType ? '' :
                    <><View className='create_button' onClick={() => { openItem('') }}></View><i className='create_shadow'></i></>
            }
        </View>
    )
}

export default App